package com.jumi.microservice.service.logistics.express;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.domain.ExpressDataDTO;
import com.jumi.microservice.dto.logistics.Logistics;
import com.jumi.microservice.dto.logistics.LogisticsSearchRequest;
import com.jumi.microservice.dto.logistics.LogisticsSearchResponse;
import com.jumi.microservice.entity.LogisticsGoods;
import com.jumi.microservice.mapper.LogisticsGoodsMapper;
import com.jumi.microservice.service.BasicDataApi;
import com.jumi.microservice.service.IAfterService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author by mazhao
 * @Classname ExpressTool
 * @Description TODO
 * @Date 2020/8/22 10:21
 */
@Component
public class ExpressTool implements CommandLineRunner {

    private Map<String, Express> expressMap = new HashMap<>();

    @Resource
    private ApplicationContext applicationContext;

    @Resource
    LogisticsGoodsMapper logisticsGoodsMapper;

    @DubboReference
    BasicDataApi iExpressService;

    @DubboReference
    IAfterService iAfterService;

    @Resource
    DefaultExpress defaultExpress;

    /**
     * 管理后台快递查询
     * @param request
     * @return
     * @throws NoSuchAlgorithmException
     */
    public LogisticsSearchResponse adminSearch(LogisticsSearchRequest request) throws Exception {
        String expressCode;
        if(request.getType().equals((byte)1)){
            QueryWrapper<LogisticsGoods> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("real_logistics_no",request.getLogisticsNo());
            queryWrapper.eq("order_no",request.getOrderNo()).last("limit 1");
            LogisticsGoods  logisticsGoods = logisticsGoodsMapper.selectOne(queryWrapper);
            if(logisticsGoods==null){
                throw new BaseException(500,"快递单号不存在");
            }
            expressCode = logisticsGoods.getExpressCode();
        }else if(request.getType().equals((byte)2)){
            expressCode = iAfterService.expressCode(request.getLogisticsNo(),request.getOrderNo());
        }else if(request.getType().equals((byte)3)){
            expressCode = iAfterService.expressCompanyCode(request.getLogisticsNo(),request.getOrderNo());
        }else{
            throw new BaseException(500,"请输入正确的查询类型");
        }
        Map<String,String> map = getExpressInfoMap();
        request.setExpressCode(expressCode);
        request.setExpressName(map.get(expressCode)==null?"快递公司":map.get(expressCode));
        if (expressMap.containsKey(expressCode)) {
            LogisticsSearchResponse res = expressMap.get(expressCode).logisticsSearch(request);
            if(res.getList()==null || res.getList().isEmpty()){
                return defaultExpress.logisticsSearch(request);
            }
            return res;
        }
        return defaultExpress.logisticsSearch(request);
    }

    /**
     * 前台快递查询
     * @param request
     * @return
     * @throws NoSuchAlgorithmException
     */
    public LogisticsSearchResponse apiSearch(LogisticsSearchRequest request,String payTime) throws Exception {
        Map<String,String> map = getExpressInfoMap();
        Logistics logistics = new Logistics();
        logistics.setDesc("商品正在出库中");
        logistics.setDate("");
        Logistics logistics1 = new Logistics();
        logistics1.setDesc("订单已提交");
        logistics1.setDate(payTime);
        request.setExpressName(map.get(request.getExpressCode())==null?"快递公司":map.get(request.getExpressCode()));
        LogisticsSearchResponse res;
        if (expressMap.containsKey(request.getExpressCode())) {
            res = expressMap.get(request.getExpressCode()).logisticsSearch(request);
            if(res.getList()==null || res.getList().isEmpty()){
                res = defaultExpress.logisticsSearch(request);
                res.getList().add(logistics);
                res.getList().add(logistics1);
                return res;
            }
            res.getList().add(logistics);
            res.getList().add(logistics1);
            if(res.getLogisticsName()==null||res.getLogisticsName().isEmpty()){
                res.setLogisticsName("快递公司");
            }
            return res;
        }
        res = defaultExpress.logisticsSearch(request);
        if(res.getLogisticsName()==null||res.getLogisticsName().isEmpty()){
            res.setLogisticsName("快递公司");
        }
        res.getList().add(logistics);
        res.getList().add(logistics1);
        return res;
    }

    @Override
    public void run(String... args){
        applicationContext.getBeansOfType(Express.class).values()
                .forEach(express -> expressMap.put(express.expressCode(), express));
    }

    /**
     * 快递公司列表
     * @return
     */
    public Map<String,String> getExpressInfoMap(){
        return iExpressService.selectExpressList()
                .stream().filter(e->e.getExpressCode()!=null)
                .collect(Collectors.toMap(ExpressDataDTO::getExpressCode,ExpressDataDTO::getExpressName));
    }

}
